package com.xunyoutest.shop.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.umeng.commonsdk.statistics.common.MLog;

import java.net.NetworkInterface;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.UUID;

/**
 * Created by admin
 * content:android设备信息工具类
 * data  2018/3/1
 */

public class AndroidBuildUtils {


    private static final String TAG = "APP";
    private static AndroidBuildUtils sInstance;

    public static AndroidBuildUtils getInstance() {
        if (sInstance == null) {
            synchronized (AndroidBuildUtils.class) {
                if (sInstance == null) {
                    sInstance = new AndroidBuildUtils();
                    return sInstance;
                }
            }
        }
        return sInstance;
    }

    private AndroidBuildUtils() {
    }


    /**
     *
     *  String phoneInfo = "Product: " + android.os.Build.PRODUCT;
     phoneInfo += ", CPU_ABI: " + android.os.Build.CPU_ABI;
     phoneInfo += ", TAGS: " + android.os.Build.TAGS;
     phoneInfo += ", VERSION_CODES.BASE: " + android.os.Build.VERSION_CODES.BASE;
     phoneInfo += ", MODEL: " + android.os.Build.MODEL;
     phoneInfo += ", SDK: " + android.os.Build.VERSION.SDK;
     phoneInfo += ", VERSION.RELEASE: " + android.os.Build.VERSION.RELEASE;
     phoneInfo += ", DEVICE: " + android.os.Build.DEVICE;
     phoneInfo += ", DISPLAY: " + android.os.Build.DISPLAY;
     phoneInfo += ", BRAND: " + android.os.Build.BRAND;
     phoneInfo += ", BOARD: " + android.os.Build.BOARD;
     phoneInfo += ", FINGERPRINT: " + android.os.Build.FINGERPRINT;
     phoneInfo += ", ID: " + android.os.Build.ID;
     phoneInfo += ", MANUFACTURER: " + android.os.Build.MANUFACTURER;
     phoneInfo += ", USER: " + android.os.Build.USER;
     *
     Product: FRD-AL00, CPU_ABI: armeabi-v7a, TAGS: release-keys, VERSION_CODES.BASE: 1, MODEL: FRD-AL00, SDK: 24, VERSION.RELEASE: 7.0, DEVICE: HWFRD, DISPLAY: FRD-AL00C00B396, BRAND: honor, BOARD: FRD, FINGERPRINT: honor/FRD-AL00/HWFRD:7.0/HUAWEIFRD-AL00/C00B396:user/release-keys, ID: HUAWEIFRD-AL00, MANUFACTURER: HUAWEI, USER: test
     */

    /**
     * 判断当前应用是否是debug状态
     */

    public boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 手获取机型号  FRD-AL00
     *
     * @return
     */
    public String getModel() {
        return Build.MODEL;
    }

    /**
     * 获取手机品牌
     * honor
     *
     * @return
     */
    public String getPhoneBrand() {
        return Build.BRAND;
    }


    /**
     * 获取SDK版本
     * sdk:24
     *
     * @return
     */
    public int getSDK() {
        return Build.VERSION.SDK_INT;
    }

    /**
     * 系统版本   7.0
     *
     * @return
     */
    public String getServiceRELEASE() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取当前版本号 VersionName:1.1.0
     */

    public String getAppVersionName(Context context) {
        String versionName = "";
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            versionName = packageInfo.versionName;
            if (TextUtils.isEmpty(versionName)) {
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }


    /**
     * 获取当前版本号 VersionCode:4
     */

    public int getAppVersionCode(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 获取主板
     *
     * @return
     */
    public String getBoard() {
        return Build.BOARD;
    }

    /**
     * 获取ID
     *
     * @return
     */
    public String getID() {
        return Build.ID;
    }


    /**
     * 获取系统启动程序版本号
     *
     * @return
     */
    public String getBootloader() {
        return Build.BOOTLOADER;
    }

    /**
     * 获取 设备名称  HWFRD
     *
     * @return
     */
    public String getDevice() {
        return Build.DEVICE;
    }

    /**
     * 获取硬件制造商
     *
     * @return
     */
    public String getManufacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * [获取应用程序版本名称信息]
     *
     * @param context
     * @return 当前应用的包名
     */
    public String getPackageName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            return packageInfo.packageName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 遍历循环所有的网络接口，找到接口是 wlan0
     * 必须的权限 <uses-permission android:name="android.permission.INTERNET" />
     *
     * @return
     */
    public String getMacAddress(Context c) {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0")) {
                    continue;
                }
                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return "";
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                return getDeviceUUID();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return "02:00:00:00:00:01";
    }

    private Signature[] getRawSignature(Context c) {
        String packageName = getPackageName(c);
        if ((packageName == null) || (packageName.length() == 0)) {
            MLog.d("获取签名失败，包名为 null");
            return null;
        }
        PackageManager localPackageManager = c.getPackageManager();
        PackageInfo localPackageInfo;
        try {
            localPackageInfo = localPackageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
            if (localPackageInfo == null) {
                MLog.d("信息为 null, 包名 = " + packageName);
                return null;
            }
        } catch (PackageManager.NameNotFoundException localNameNotFoundException) {
            MLog.d("包名没有找到...");
            return null;
        }
        return localPackageInfo.signatures;
    }

    private static String getSignValidString(byte[] paramArrayOfByte) throws NoSuchAlgorithmException {
        MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
        localMessageDigest.update(paramArrayOfByte);
        return toHexString(localMessageDigest.digest());
    }

    public static String toHexString(byte[] paramArrayOfByte) {
        if (paramArrayOfByte == null) {
            return null;
        }
        StringBuilder localStringBuilder = new StringBuilder(2 * paramArrayOfByte.length);
        for (int i = 0; ; i++) {
            if (i >= paramArrayOfByte.length) {
                return localStringBuilder.toString();
            }
            String str = Integer.toString(0xFF & paramArrayOfByte[i], 16);
            if (str.length() == 1) {
                str = "0" + str;
            }
            localStringBuilder.append(str);
        }
    }


    public String sha1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            String result = hexString.toString();
            return result.substring(0, result.length() - 1);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    @SuppressLint("MissingPermission")
    public String getDeviceUUID() {
        String serial = null;
        String m_szDevIDShort = "35" +
                Build.BOARD.length() % 10 + Build.BRAND.length() % 10 +

                Build.CPU_ABI.length() % 10 + Build.DEVICE.length() % 10 +

                Build.DISPLAY.length() % 10 + Build.HOST.length() % 10 +

                Build.ID.length() % 10 + Build.MANUFACTURER.length() % 10 +

                Build.MODEL.length() % 10 + Build.PRODUCT.length() % 10 +

                Build.TAGS.length() % 10 + Build.TYPE.length() % 10 +

                Build.USER.length() % 10; //13 位

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                serial = Build.getSerial();
            } else {
                serial = Build.SERIAL;
            }
            //API>=9 使用serial号
            return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
        } catch (Exception exception) {
            //serial需要一个初始化
            serial = "serial"; // 随便一个初始化
        }
        //使用硬件信息拼凑出来的15位号码
        return new UUID(m_szDevIDShort.hashCode(), serial.hashCode()).toString();
    }

    public void printDeviceLog(Context c) {
        MLog.d(TAG,"应用是否是debug状态-->" + isApkInDebug(c));
        MLog.d(TAG,"手机型号-->" + getModel());
        MLog.d(TAG,"手机品牌-->" + getPhoneBrand());
        MLog.d(TAG,"SDK版本-->" + getSDK());
        MLog.d(TAG,"系统版本-->" + getServiceRELEASE());
        MLog.d(TAG,"VersionName-->" + getAppVersionName(c));
        MLog.d(TAG,"VersionCode-->" + getAppVersionCode(c));
        MLog.d(TAG,"Mac地址-->" + getMacAddress(c));
        MLog.d(TAG,"包名-->" + getPackageName(c));
        MLog.d(TAG,"Device UUID-->" + getDeviceUUID());
        DisplayMetrics dm = c.getResources().getDisplayMetrics();
        MLog.d(TAG,"宽度-->" + dm.widthPixels);
        MLog.d(TAG,"高度-->" + dm.heightPixels);
        try {
            MLog.d(TAG,"签名md5-->" + getSignValidString(getRawSignature(c)[0].toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        MLog.d(TAG,"SHA1-->" + sha1(c));
    }
}
